package lockfile

import "os"

const (
	perm = os.FileMode(0640)
)

type FileLock struct {
	f *os.File
}

func New(name string) (*FileLock, error) {
	file, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, perm)
	if err != nil {
		return nil, err
	}
	return &FileLock{f: file}, nil
}

func (fl *FileLock) Destroy() {
	fl.f.Close()
	fl.f = nil
}

func (fl *FileLock) Lock(block bool) error {
	return lockFile(fl.f, block)
}

func (fl *FileLock) Unlock() error {
	return unlockFile(fl.f)
}

func (fl *FileLock) GetFile() *os.File {
	return fl.f
}
